/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.QuickTips.init();
var _pageSize = 20;
var _pageSizeSmall = 10;
var fieldName = ['id', 'name', 'x', 'y', 'h', 'pointTypeId', 'pointType', 'pointType2Id', 'pointType2', 'voltageLevelId', 'voltageLevelName', 'status', 'note', 'updateTime',
    'creatTime', 'orgCode', 'deptId', 'fromId', 'lowerLimit', 'upperLimit', 'pointArea', 'pointPosition', 'userName', 'publicName', 'deviceId', 'code', 'company', 'installSite',
    'manufactoryName', 'model', 'commTypeName', 'mobileNo', 'ip', 'terminalNo', 'installTime', 'checkTime', 'effectTime', 'stopTime', 'stopReason', 'expireTime', 'produceTime', 'port',
    'uniqueCode', 'zbm', 'adminAreaCode', 'channel', 'runTime', 'subCompany', 'shortName', 'stationVoltageLevel', 'realName', 'deviceType', 'deviceNo', 'stationName', 'modelId',
    'startStatusCh', 'reportStatusCh', 'stationVoltageLevelId', 'protocolName', 'protocolCode'];
var fieldLabel = ['ID', '监测点名称', '经度', '纬度', '高度', '监测点类型ID（类别1）', '监测点类型(类别1)', '电网类型ID（类别2）', '电网类别（类别2）', '电压等级ID', '电压等级', '状态',
    '备注', '记录的更新时间', '记录的创建时间', '机构编码', '所属部门编码', '上级监测点', '电压下限', '电压上限', '用户名称', '公变名称', '设备ID', '监测点编码', '供电局', '安装位置',
    '生产厂家', '装置型号', '通信方式', '通信卡号', '装置IP', '终端地址', '安装日期', '校验日期', '生效日期', '停用日期', '停用原因', '有效期', '出厂日期', '装置端口', '唯一码', '组编码', '行政区域码',
    '通道', '投运日期', '部门分县局', '所属供电所名称', '所属变电站电压等级', '管理人员', '装置类别', '在线离线', '上报观测', '启用停用', '装置编码', '所属变电站名称', '协议名称', '协议编码'];
var fieldType = [];
var saveServlet = basePath + 'servlet/system/PointSave';
var loadServlet = basePath + 'servlet/system/PointLoad';
var deleteServlet = basePath + 'servlet/system/PointDel';
var unbindServlet = basePath + 'servlet/point/PointUnbind';
var deviceSaveServlet = basePath + 'servlet/system/DeviceSave';
var theme = '监测点';
var _title = currentOrgName + theme + '管理';
var now = new Date();
var modelStore = new Ext.data.JsonStore({
    url: basePath + 'servlet/common/SimpleFormInfoLoad',
    baseParams: {id: 'id', name: 'model', tableName: 't_model'},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'model']
});

var modelCombo = {
    name: 'model',
    xtype: 'combo',
    store: modelStore,
    id: 'ModelCombo',
    displayField: 'model',
    valueField: 'id',
    hiddenName: 'modelId',
    //typeAhead: true,
    autoSelect: true,
    //editable: true,
    //minChars:1,
    //autoLoad:true,
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '型号',
    emptyText: '请选择型号...',
    selectOnFocus: true,
    listeners: {
        select: function(combo, record, index) {

            if (record.get('model') === 'DT3') {
                modelDT3();
            } else if (record.get('model') === 'DT4-2') {
                modelDT4();
            } else {

            }
        }
    }

};

function modelDT3() {
    Ext.getCmp('AdminAreaCode').disable();
    Ext.getCmp('AdminAreaCode').hide();
    Ext.getCmp('zbm').disable();
    Ext.getCmp('zbm').hide();
    Ext.getCmp('Ip').disable();
    Ext.getCmp('Ip').hide();
    Ext.getCmp('UniqueCode').enable();
    Ext.getCmp('UniqueCode').show();
}

function modelDT4() {
    Ext.getCmp('UniqueCode').disable();
    Ext.getCmp('UniqueCode').hide();
    Ext.getCmp('AdminAreaCode').enable();
    Ext.getCmp('AdminAreaCode').show();
    Ext.getCmp('zbm').enable();
    Ext.getCmp('zbm').show();
    Ext.getCmp('Ip').enable();
    Ext.getCmp('Ip').show();
}

function modelNew() {
    Ext.getCmp('AdminAreaCode').disable();
    Ext.getCmp('AdminAreaCode').hide();
    Ext.getCmp('zbm').disable();
    Ext.getCmp('zbm').hide();
    Ext.getCmp('Ip').disable();
    Ext.getCmp('Ip').hide();
    Ext.getCmp('UniqueCode').disable();
    Ext.getCmp('UniqueCode').hide();

    Ext.getCmp('DeviceNo').setValue("");
    Ext.getCmp('ModelCombo').setValue("");
    Ext.getCmp('AdminAreaCode').setValue("");
    Ext.getCmp('terminalNo').setValue("");
    Ext.getCmp('zbm').setValue("");
    Ext.getCmp('installSite').setValue("");
    Ext.getCmp('MobileNo').setValue("");
    Ext.getCmp('UniqueCode').setValue("");
    Ext.getCmp('Ip').setValue("");
    Ext.getCmp('Port').setValue("");
    Ext.getCmp('Channel').setValue("");
    Ext.getCmp('RunTime').setValue("");
    Ext.getCmp('ProduceTime').setValue("");
    Ext.getCmp('CheckTime').setValue("");
    Ext.getCmp('ExpireTime').setValue("");
    Ext.getCmp('Note').setValue("");
}

var comProtocolStore = new Ext.data.JsonStore({
    url: '../../servlet/common/SimpleInfoLoad',
    baseParams: {id: 'protocolCode', name: 'protocolName', tableName: 't_commProtocol'},
    autoLoad: true,
    root: 'data',
    fields: ['protocolCode', 'protocolName']
});

var comProtocolCombo = {
    name: 'protocolName',
    xtype: 'combo',
    store: comProtocolStore,
    id: 'ComProtocolCombo',
    displayField: 'protocolName',
    valueField: 'protocolCode',
    hiddenName: 'protocolCode',
    autoSelect: true,
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '协议名称',
    emptyText: '请选择协议名称...',
    selectOnFocus: true
};

var deviceType = 1;
var setDeviceForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'SetDeviceForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: 'id',
                    xtype: 'textfield',
                    fieldLabel: 'ID',
                    hidden: true
                }
                , {
                    name: 'deviceNo',
                    id: 'DeviceNo',
                    xtype: 'textfield',
                    fieldLabel: '装置编码',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }
                , modelCombo,
                comProtocolCombo,
                {
                    name: 'adminAreaCode',
                    id: 'AdminAreaCode',
                    xtype: 'textfield',
                    fieldLabel: '区域码',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 5,
                    maxLengthText: '不能多于5个字符,1个汉字占用2个字符'
                }, {
                    name: 'terminalNo',
                    id: 'terminalNo',
                    xtype: 'textfield',
                    fieldLabel: '终端地址',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 10,
                    maxLengthText: '不能多于10个字符,1个汉字占用2个字符'
                }, {
                    name: 'zbm',
                    id: 'zbm',
                    xtype: 'textfield',
                    fieldLabel: '组编码',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'installSite',
                    id: 'installSite',
                    xtype: 'textfield',
                    fieldLabel: '安装地点',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                }, {
                    name: 'mobileNo',
                    id: 'MobileNo',
                    xtype: 'textfield',
                    fieldLabel: '手机号码',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    regex: /^([0-9]+)$/,
                    regexText: "手机号码只能输入数字",
                    maxLength: 20,
                    maxLengthText: '不能多于20个字符,1个汉字占用2个字符'
                }, {
                    name: 'uniqueCode',
                    id: 'UniqueCode',
                    xtype: 'textfield',
                    fieldLabel: '唯一码',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'ip',
                    id: 'Ip',
                    xtype: 'textfield',
                    fieldLabel: 'IP地址',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 20,
                    maxLengthText: '不能多于20个字符,1个汉字占用2个字符'
                }, {
                    name: 'port',
                    id: 'Port',
                    xtype: 'numberfield',
                    fieldLabel: '端口',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写数字',
                    maxValue: 65535,
                    minValue: 1,
                    maxText: '端口在1-65535之间',
                    minText: '端口在1-65535之间'
                }, {
                    name: 'channel',
                    id: 'Channel',
                    xtype: 'textfield',
                    fieldLabel: '通道',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 1,
                    maxLengthText: '不能多于1个字符,1个汉字占用2个字符'
                }, {
                    name: 'runTime',
                    id: 'RunTime',
                    xtype: 'datefield',
                    fieldLabel: '投运日期',
                    format: 'Y-m-d H:i:s',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'produceTime',
                    id: 'ProduceTime',
                    xtype: 'datefield',
                    fieldLabel: '出厂日期',
                    format: 'Y-m-d H:i:s',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'checkTime',
                    id: 'CheckTime',
                    xtype: 'datefield',
                    fieldLabel: '校验日期',
                    format: 'Y-m-d H:i:s',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'expireTime',
                    id: 'ExpireTime',
                    xtype: 'datefield',
                    fieldLabel: '有效期',
                    format: 'Y-m-d H:i:s',
                    width: 160,
                    allowBlank: false,
                    blankText: '必须填写'
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winSetDevice.hide();
                                store.reload();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        if (deviceType === 1)
                            submitConfig.params.cmd = 'createDevice';
                        else {
                            submitConfig.params.id = checkboxSel.getSelected().get("deviceId");
                            submitConfig.params.cmd = 'updateDevice';
                        }
                        submitConfig.params.pointId = checkboxSel.getSelected().get("id");
                        Ext.getCmp('SetDeviceForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winSetDevice.hide();
                    }
                }]
        }
);
var winSetDevice = new Ext.Window({
    layout: 'form',
    modal: true,
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [setDeviceForm]
});
var pointAreaStore = new Ext.data.SimpleStore({
    fields: ['pointArea'],
    data: [['市中心'], ['市区'], ['城镇'], ['农村']]
});

var pointPositionStore = new Ext.data.SimpleStore({
    fields: ['pointPosition'],
    data: [['系统端'], ['用户端'], ['首端'], ['末端'], ['重要用户']]
});

var bPointPositionStore = new Ext.data.SimpleStore({
    fields: ['bPointPosition'],
    data: [['系统端'], ['用户端']]
});
var bPointPositionComboF = {
    name: 'pointPosition',
    id: 'BPointPosition',
    xtype: 'combo',
    fieldLabel: '监测测点位置',
    width: 180,
    triggerAction: 'all',
    loadingText: '测点位置',
    allowBlank: false,
    blankText: '不允许为空',
    emptyText: '请选择测点位置...',
    editable: false,
    store: bPointPositionStore,
    displayField: 'bPointPosition',
    valueField: 'bPointPosition',
    mode: 'local',
    forceSelection: true,
    selectOnFocus: true
};

var dPointPositionStore = new Ext.data.SimpleStore({
    fields: ['dPointPosition'],
    data: [['首端'], ['末端'], ['重要用户']]
});

var dPointPositionComboF = {
    name: 'pointPosition',
    id: 'DPointPosition',
    xtype: 'combo',
    fieldLabel: '监测测点位置',
    width: 180,
    triggerAction: 'all',
    loadingText: '测点位置',
    allowBlank: false,
    blankText: '不允许为空',
    emptyText: '请选择测点位置...',
    editable: false,
    store: dPointPositionStore,
    displayField: 'dPointPosition',
    valueField: 'dPointPosition',
    mode: 'local',
    forceSelection: true,
    selectOnFocus: true
};

var pointTypeStore = new Ext.data.JsonStore({
    url: basePath + 'servlet/common/SimpleFormInfoLoad',
    baseParams: {id: 'id', name: 'name', tableName: 't_pointType'},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'name']
});
var pointTypeComboF = {
    name: 'pointType',
    xtype: 'combo',
    store: pointTypeStore,
    id: 'PointTypeComboF',
    displayField: 'name',
    valueField: 'id',
    hiddenName: 'pointTypeId',
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '监测点类型',
    emptyText: '请选择监测点类型...',
    width: 160,
    selectOnFocus: true,
    listeners: {
        select: function(combo, record, index) {
            if (record.get('name') === 'A类') {
                pointTypeA();
            } else if (record.get('name') === 'B类') {
                pointTypeB();
            } else if (record.get('name') === 'C类') {
                pointTypeC();
            } else if (record.get('name') === 'D类') {
                pointTypeD();
            } else {
                pointTypeE();
            }
        }
    }
};
var pointType2Store = new Ext.data.JsonStore({
    url: basePath + 'servlet/common/SimpleInfoLoad',
    baseParams: {id: 'id', name: 'name', tableName: 't_pointType2'},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'name']
});
var pointType2ComboF = {
    xtype: 'combo',
    store: pointType2Store,
    id: 'PointType2ComboF',
    displayField: 'name',
    valueField: 'id',
    hiddenName: 'pointType2Id',
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '城农网类别',
    emptyText: '请选择城农网类别...',
    width: 160,
    selectOnFocus: true
};
var voltageLevelStore = new Ext.data.JsonStore({
    url: basePath + 'servlet/common/SimpleFormInfoLoad',
    baseParams: {id: 'id', name: 'name,lowerLimit,upperLimit,pointTypeId,pointTypeName', tableName: 'v_voltageLevel'},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'name', 'lowerLimit', 'upperLimit', 'pointTypeId', 'pointTypeName']
});
var voltageLevelComboF = {
    xtype: 'combo',
    store: voltageLevelStore,
    id: 'VoltageLevelComboF',
    displayField: 'name',
    valueField: 'id',
    hiddenName: 'voltageLevelId',
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '电压等级',
    emptyText: '请选择电压等级...',
    width: 160,
    selectOnFocus: true,
    listeners: {
        select: function(combo, record, index) {
            //alert(record.get('lowerLimit'));
            //alert(record.get('UpperLimit'));
            Ext.getCmp('LowerLimit').setValue(record.get('lowerLimit'));
            Ext.getCmp('UpperLimit').setValue(record.get('upperLimit'));
            Ext.getCmp('PointTypeComboF').setValue(record.get('pointTypeId'));
            //Ext.getCmp('PointTypeComboF').fireEvent("select");

            temp = record.get('pointTypeName');
            if (temp === 'A类') {
                pointTypeA();
            } else if (temp === 'B类') {
                pointTypeB();
            } else if (temp === 'C类') {
                pointTypeC();
            } else if (temp === 'D类') {
                pointTypeD();
            } else {
                pointTypeE();
            }
        }
    }
};
var voltageLevelCombo2F = {
    xtype: 'combo',
    store: voltageLevelStore,
    id: 'VoltageLevelCombo2F',
    displayField: 'name',
    valueField: 'id',
    hiddenName: 'stationVoltageLevelId',
    mode: 'remote',
    forceSelection: true,
    allowBlank: false,
    blankText: '不允许为空',
    triggerAction: 'all',
    fieldLabel: '所属变电站电压等级',
    emptyText: '请选择电压等级...',
    selectOnFocus: true,
    width: 160,
    listeners: {
        select: function(combo, record, index) {
            //alert(record.get('lowerLimit'));
            //alert(record.get('UpperLimit'));
            //Ext.getCmp('LowerLimit').setValue(record.get('lowerLimit'));
            //Ext.getCmp('UpperLimit').setValue(record.get('upperLimit'));
            //Ext.getCmp('PointTypeCombo').setValue(record.get('pointTypeId'));
        }
    }
};
var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: fieldName[0],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[0],
                    hidden: true
                }, {
                    name: 'code',
                    id: 'code',
                    xtype: 'textfield',
                    width: 180,
                    fieldLabel: '监测点编码',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'name',
                    id: 'Name',
                    xtype: 'textfield',
                    width: 180,
                    fieldLabel: '监测点名称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                },
                voltageLevelComboF,
                pointTypeComboF, {
                    name: 'lowerLimit',
                    id: 'LowerLimit',
                    width: 180,
                    xtype: 'textfield',
                    fieldLabel: '电压下限定值',
                    allowBlank: false,
                    blankText: '自动填写'
                }, {
                    name: 'upperLimit',
                    id: 'UpperLimit',
                    width: 180,
                    xtype: 'textfield',
                    fieldLabel: '电压上限定值',
                    allowBlank: false,
                    blankText: '自动填写'
                }, pointType2ComboF,
                voltageLevelCombo2F,
                {
                    name: 'stationName',
                    id: 'StationName',
                    xtype: 'textfield',
                    width: 180,
                    fieldLabel: '所属变电站名称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 10,
                    maxLengthText: '不能多于10个字符,1个汉字占用2个字符'
                },
                {
                    name: 'pointArea',
                    id: 'PointArea',
                    xtype: 'combo',
                    fieldLabel: '测点地域',
                    width: 180,
                    triggerAction: 'all',
                    emptyText: '请选择测点地域...',
                    allowBlank: false,
                    blankText: '不允许为空',
                    editable: false,
                    store: pointAreaStore,
                    displayField: 'pointArea',
                    valueField: 'pointArea',
                    mode: 'local'
                },
                bPointPositionComboF,
                dPointPositionComboF,
//                {
//                    name: 'pointPosition',
//                    id: 'PointPosition',
//                    xtype: 'combo',
//                    fieldLabel: '监测测点位置',
//                    width: 180,
//                    triggerAction: 'all',
//                    loadingText: '测点位置',
//                    allowBlank: false,
//                    blankText: '不允许为空',
//                    emptyText: '请选择测点位置...',
//                    editable: false,
//                    store: pointPositionStore,
//                    displayField: 'pointPosition',
//                    valueField: 'pointPosition',
//                    mode: 'local'
//                },
                {
                    name: 'userName',
                    id: 'UserName',
                    width: 180,
                    xtype: 'textfield',
                    fieldLabel: '用户名称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'publicName',
                    id: 'PublicName',
                    width: 180,
                    xtype: 'textfield',
                    fieldLabel: '公变名称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'effectTime',
                    id: 'EffectTime',
                    width: 180,
                    xtype: 'datefield',
                    fieldLabel: '测点生效日期',
                    format: 'Y-m-d',
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'installTime',
                    id: 'InstallTime',
                    width: 180,
                    xtype: 'datefield',
                    fieldLabel: '安装日期',
                    format: 'Y-m-d',
                    allowBlank: false,
                    blankText: '必须填写'
                }, {
                    name: 'note',
                    id: 'Note',
                    xtype: 'textfield',
                    fieldLabel: '备注',
                    width: 180,
                    allowBlank: true,
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {pointType2Id0: Ext.getCmp('PointType2ComboF').getRawValue()}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        if (type === 1)
                            submitConfig.params.cmd = 'create';
                        else {
                            //submitConfig.params.id = checkboxSel.getSelected().get("id");
                            submitConfig.params.cmd = 'update';
                        }
                        //alert(submitConfig);
//                        if(Ext.getCmp('UserName').getValue()===null||Ext.getCmp('UserName').getValue()===''){
//                            Ext.getCmp('UserName').markInvalid();
//                            return;
//                        }
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                        //alert('end');
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);
var win = new Ext.Window({
    layout: 'form',
    width: 400,
    autoHeight: true,
    modal: true,
    closeAction: 'hide',
    items: [inputForm]
});
var type = 1; //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
function addnew() {
    type = 1;
    win.setTitle('增加' + theme);
    //if (updated)
    // Ext.getCmp('addusr-form').getForm().getEl().dom.reset();
    Ext.getCmp('input-form').getForm().reset();
    // Ext.getCmp(fieldName[13]).setValue(currentManuFactoryName);
    pointTypeNew();
    win.show();
}

function pointTypeNew() {
    Ext.getCmp('PointType2ComboF').disable();
    Ext.getCmp('PointType2ComboF').hide();
    Ext.getCmp('BPointPosition').disable();
    Ext.getCmp('BPointPosition').hide();
    Ext.getCmp('DPointPosition').disable();
    Ext.getCmp('DPointPosition').hide();
    Ext.getCmp('UserName').disable();
    Ext.getCmp('UserName').hide();
    Ext.getCmp('PublicName').disable();
    Ext.getCmp('PublicName').hide();

    Ext.getCmp('code').setValue("");
    Ext.getCmp('Name').setValue("");
    Ext.getCmp('UserName').setValue("");
    Ext.getCmp('PublicName').setValue("");
    Ext.getCmp('StationName').setValue("");
    Ext.getCmp('PointTypeComboF').setValue("");
    Ext.getCmp('UpperLimit').setValue("");
    Ext.getCmp('LowerLimit').setValue("");
    Ext.getCmp('PointType2ComboF').setValue("");
    Ext.getCmp('DPointPosition').setValue("");
    Ext.getCmp('BPointPosition').setValue("");
    Ext.getCmp('VoltageLevelComboF').setValue("");
    Ext.getCmp('VoltageLevelCombo2F').setValue("");
    Ext.getCmp('PointArea').setValue("");
    Ext.getCmp('EffectTime').setValue("");
    Ext.getCmp('InstallTime').setValue("");
    Ext.getCmp('Note').setValue("");
}

function pointTypeA() {
    Ext.getCmp('PointType2ComboF').disable();
    Ext.getCmp('PointType2ComboF').hide();
    Ext.getCmp('BPointPosition').disable();
    Ext.getCmp('BPointPosition').hide();
    Ext.getCmp('DPointPosition').disable();
    Ext.getCmp('DPointPosition').hide();
    Ext.getCmp('UserName').disable();
    Ext.getCmp('UserName').hide();
    Ext.getCmp('PublicName').disable();
    Ext.getCmp('PublicName').hide();
}

function pointTypeB() {
    Ext.getCmp('PointType2ComboF').disable();
    Ext.getCmp('PointType2ComboF').hide();
    Ext.getCmp('BPointPosition').enable();
    Ext.getCmp('BPointPosition').show();
    Ext.getCmp('DPointPosition').disable();
    Ext.getCmp('DPointPosition').hide();
    Ext.getCmp('UserName').enable();
    Ext.getCmp('UserName').show();
    Ext.getCmp('PublicName').disable();
    Ext.getCmp('PublicName').hide();

    temp = checkboxSel.getSelected().get('pointPosition');
    Ext.getCmp('BPointPosition').setValue(temp);
}

function pointTypeC() {
    Ext.getCmp('PointType2ComboF').disable();
    Ext.getCmp('PointType2ComboF').hide();
    Ext.getCmp('BPointPosition').disable();
    Ext.getCmp('BPointPosition').hide();
    Ext.getCmp('DPointPosition').disable();
    Ext.getCmp('DPointPosition').hide();
    Ext.getCmp('UserName').enable();
    Ext.getCmp('UserName').show();
    Ext.getCmp('PublicName').disable();
    Ext.getCmp('PublicName').hide();
}

function pointTypeD() {
    Ext.getCmp('PointType2ComboF').enable();
    Ext.getCmp('PointType2ComboF').show();
    Ext.getCmp('BPointPosition').disable();
    Ext.getCmp('BPointPosition').hide();
    Ext.getCmp('DPointPosition').enable();
    Ext.getCmp('DPointPosition').show();
    Ext.getCmp('UserName').disable();
    Ext.getCmp('UserName').hide();
    Ext.getCmp('PublicName').enable();
    Ext.getCmp('PublicName').show();

    temp = checkboxSel.getSelected().get('pointPosition');
    Ext.getCmp('DPointPosition').setValue(temp);
}

function pointTypeE() {
    Ext.getCmp('PointType2ComboF').enable();
    Ext.getCmp('PointType2ComboF').show();
    Ext.getCmp('BPointPosition').enable();
    Ext.getCmp('BPointPosition').show();
    Ext.getCmp('DPointPosition').disable();
    Ext.getCmp('DPointPosition').hide();
    Ext.getCmp('UserName').enable();
    Ext.getCmp('UserName').show();
    Ext.getCmp('PublicName').enable();
    Ext.getCmp('PublicName').show();

    temp = checkboxSel.getSelected().get('pointPosition');
    Ext.getCmp('DPointPosition').setValue(temp);
}

function update() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                modal: true,
                closeAction: 'hide',
                items: [inputForm]
            });
        }

//        if (type === 1) {
//            Ext.getCmp('code').setValue("");
//            Ext.getCmp('Name').setValue("");
//        }
//alert(checkboxSel.getSelected().get('code'));
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        temp = checkboxSel.getSelected().get('effectTime');
        r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
        Ext.getCmp('EffectTime').setValue(r);
        temp = checkboxSel.getSelected().get('installTime');
        r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
        Ext.getCmp('InstallTime').setValue(r);
        win.setTitle('修改' + theme);

        temp = checkboxSel.getSelected().get('pointType');

        if (temp === 'A类') {
            pointTypeA();
        } else if (temp === 'B类') {
            pointTypeB();
        } else if (temp === 'C类') {
            pointTypeC();
        } else if (temp === 'D类') {
            pointTypeD();
        } else {
            pointTypeE();
        }

        win.show();
        //Ext.getDom('win-title').innerHTML='修改监控设备信息';
    }
}

function getIds(rs) {
    var jsonData = "";
    var jsonDataDevices = "";
    for (var i = 0, len = rs.length; i < len; i++) {
        var ss = rs[i].get("id"); //这里为Grid数据源的Id列
        var ssDevices = rs[i].get("deviceId");
        if (i === 0) {
            jsonData = jsonData + ss;
            jsonDataDevices = jsonDataDevices + ssDevices;
        }
        else {
            jsonData = jsonData + "," + ss;
            jsonDataDevices = jsonDataDevices + "," + ssDevices;
        }
    }
    return {pointIds: jsonData, deviceIds: jsonDataDevices};
}

function getPointNames(rs, n) {
    var jsonData = "";
    for (var i = 0, len = rs.length; i < len; i++) {
        var ss = rs[i].get(n);
        if (i === 0) {
            jsonData = jsonData + ss;
        }
        else {
            jsonData = jsonData + "," + ss;
        }
    }
    return jsonData;
}

var batchUpdateForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'BatchUpdateForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            layout: 'table',
            layoutConfig: {
                columns: 3
            },
            url: saveServlet,
            items: [
                {
                    xtype: 'label',
                    text: '所选监测点名称',
                    width: 100
                },
                {
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesBatchUpdate',
                    height: 60,
                    readOnly: true,
                    diable: true,
                    colspan: 2,
                    width: 450,
                    style: {
                        marginLeft: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '所属供电站名称',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stationName',
                    xtype: 'textfield',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stationNameChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '公变名称',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'publicName',
                    xtype: 'textfield',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'publicNameChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '测点地域',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'pointArea',
                    xtype: 'textfield',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'pointAreaChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '监测测点位置',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'pointPosition',
                    xtype: 'textfield',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'pointPositionChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '生效日期',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'effectTime',
                    xtype: 'datefield',
                    format: 'Y-m-d',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'effectTimeChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '安装日期',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'installTime',
                    xtype: 'datefield',
                    format: 'Y-m-d',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'installTimeChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '停用日期',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stopTime',
                    xtype: 'datefield',
                    format: 'Y-m-d',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stopTimeChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    xtype: 'label',
                    text: '停用原因',
                    width: 100,
                    style: {
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stopReason',
                    xtype: 'textfield',
                    width: 400,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                },
                {
                    name: 'stopReasonChecked',
                    xtype: 'checkbox',
                    width: 50,
                    style: {
                        marginLeft: '10px',
                        marginTop: '10px'
                    }
                }

            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-control_play',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                winBatchUpdate.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var ids = getIds(checkboxSel.getSelections());
                        //alert(ids.pointIds);
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.cmd = 'batch';
                        Ext.getCmp('BatchUpdateForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winBatchUpdate.hide();
                    }
                }]
        }
);
var winBatchUpdate = new Ext.Window({
    title: '批量修改测点信息',
    layout: 'form',
    width: 600,
    autoHeight: true,
    closeAction: 'hide',
    modal: true,
    items: [batchUpdateForm]
});
function batchUpdate() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "请先选择监测点");
    }
    else {
        Ext.getCmp('BatchUpdateForm').getForm().reset();
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesBatchUpdate').setValue(pointNames);
        winBatchUpdate.show();
    }
}

function remove() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统消息", "您还没有选择，需要先选择才能删除");
    }
    else {
        if (loadCmd === 'normal') {
            msg = "确实要删除所选的记录吗?";
        } else {
            msg = "删除监测点，将删除相关监测点下的所有数据。包括监测点日数据，月数据等等<br/>请谨慎操作！！！";
        }
        Ext.MessageBox.confirm('提示', msg, function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                var jsonDataDevices = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    var ssDevices = records[i].get("deviceId");
                    if (i === 0) {
                        jsonData = jsonData + ss;
                        jsonDataDevices = jsonDataDevices + ssDevices;
                    }
                    else {
                        jsonData = jsonData + "," + ss;
                        jsonDataDevices = jsonDataDevices + "," + ssDevices;
                    }
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,loadCmd: loadCmd, ids: jsonData, deviceIds: jsonDataDevices},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                store.reload(); //重新load数据   	

                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}
function removeFull() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统消息", "您还没有选择，需要先选择才能删除");
    }
    else {

        msg = "删除监测点及设备信息，将删除相关监测点下的所有数据。包括监测点日数据，月数据等等<br/>请谨慎操作！！！";

        Ext.MessageBox.confirm('提示', msg, function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                var jsonDataDevices = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    var ssDevices = records[i].get("deviceId");
                    if (i === 0) {
                        jsonData = jsonData + ss;
                        jsonDataDevices = jsonDataDevices + ssDevices;
                    }
                    else {
                        jsonData = jsonData + "," + ss;
                        jsonDataDevices = jsonDataDevices + "," + ssDevices;
                    }
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,loadCmd: loadCmd, isFull: true, ids: jsonData, deviceIds: jsonDataDevices},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                store.reload(); //重新load数据  
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }
                        } else {
                            Ext.MessageBox.alert("提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}


function restore() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能恢复");
    }
    else {
        Ext.MessageBox.confirm('提示', '您确实想恢复所选记录吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                var jsonDataDevices = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    var ssDevices = records[i].get("deviceId");
                    if (i === 0) {
                        jsonData = jsonData + ss;
                        jsonDataDevices = jsonDataDevices + ssDevices;
                    }
                    else {
                        jsonData = jsonData + "," + ss;
                        jsonDataDevices = jsonDataDevices + "," + ssDevices;
                    }
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: saveServlet, //提交的删除地址
                    params: {token:token,token1:token1,cmd: "restore", ids: jsonData, deviceIds: jsonDataDevices},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功恢复！");
                                store.reload(); //重新load数据
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录恢复失败！");
                        }
                    }
                });
            }
        });
    }
}


var orgStore = new Ext.data.JsonStore({
    url: basePath + 'servlet/common/SimpleFormInfoLoad',
    baseParams: {id: 'orgCode', name: 'name', tableName: 't_org', condition: " where orgCode like '" + currentOrgCode + "%' order by orgCode"},
    autoLoad: true,
    root: 'data',
    fields: ['orgCode', 'name']
});
var changeOrgForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'ChangeOrgForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesChangeOrg',
                    width: 180,
                    height: 250,
                    readOnly: true,
                    diable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
                , {
                    xtype: 'combo',
                    store: orgStore,
                    id: 'OrgCombo',
                    displayField: 'name',
                    valueField: 'orgCode',
                    hiddenName: 'orgCode',
                    mode: 'remote',
                    forceSelection: true,
                    triggerAction: 'all',
                    fieldLabel: '所属单位',
                    emptyText: '请选择所属单位...',
                    selectOnFocus: true,
                    width: 160
                }
            ],
            buttons: [{
                    text: '确定',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                winChangeOrg.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        //alert(ids.pointIds);
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.cmd = 'changeOrg';
                        Ext.getCmp('ChangeOrgForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winChangeOrg.hide();
                    }
                }]
        }
);
var winChangeOrg = new Ext.Window({
    title: "监测点单位变更",
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    modal: true,
    items: [changeOrgForm]
});
function changeOrg() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能配置装置");
    }
    else {
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesChangeOrg').setValue(pointNames);
        winChangeOrg.show();
    }
}

var storeDevice = new Ext.data.JsonStore({
    url: basePath + 'servlet/system/DeviceLoad',
    root: 'data',
    idProperty: 'id',
    totalProperty: 'count',
    fields: ['id', 'deviceNo', 'modelId', 'installSite', 'mobileNo', 'terminalNo', 'uniqueCode', 'adminAreaCode', 'ip', 'port', 'pointId', 'point', 'runTime', 'checkTime', 'expireTime', 'status', 'note', 'updateTime', 'createTime', 'orgCode', 'model', 'commTypeName', 'manufactoryName', 'shortName']
});
var checkboxSelDevice = new Ext.grid.CheckboxSelectionModel({singleSelect: true});
var deviceGrid = new Ext.grid.GridPanel({
    store: storeDevice,
    sm: checkboxSelDevice,
    //autoHeight: true,
    height: 350,
    //disableSelection:true,
    columns: [
        checkboxSelDevice,
        {header: 'ID', sortable: true, dataIndex: 'id', hidden: true},
        {header: '装置编号', width: 80, sortable: true, dataIndex: 'deviceNo'},
        {header: '安装地址', width: 80, sortable: true, dataIndex: 'installSite'},
        {header: '手机号码', width: 80, sortable: true, dataIndex: 'mobileNo'},
        {header: '装置编码', width: 100, sortable: true, dataIndex: 'deviceNo'},
        {header: '终端地址', width: 80, sortable: true, dataIndex: 'terminalNo'},
        {header: '行政区域码', width: 80, sortable: true, dataIndex: 'adminAreaCode'},
        {header: '唯一码', width: 120, sortable: true, dataIndex: 'uniqueCode'},
        {header: '型号', width: 80, sortable: true, dataIndex: 'model'},
        {header: '生产厂家', width: 80, sortable: true, dataIndex: 'manufactoryName'}
    ],
    //autoExpandColumn: fieldName[2],
    //renderTo: Ext.getBody(),
    //width: 780,
    //height: 590,
    loadMask: true,
    tbar: new Ext.Toolbar([
    ]),
    bbar: new Ext.PagingToolbar({
        pageSize: _pageSizeSmall,
        store: storeDevice,
        displayInfo: true,
        displayMsg: '显示记录：{0} - {1}   总记录：{2}',
        emptyMsg: "目前没有未启用设备信息"
    })
});
var deviceWin = new Ext.Window({
    title: '设置装置',
    id: 'DeviceWin',
    width: 700,
    height: 350,
    modal: true,
    autoHeight: true,
    resizable: true,
    layout: 'fit',
    closable: true,
    closeAction: 'hide',
    items: [deviceGrid],
    buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function() {

                var recordDevice = checkboxSelDevice.getSelected();
                var recordPoint = checkboxSel.getSelected();
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: saveServlet,
                    params: {token:token,token1:token1,deviceId: recordDevice.get('id'), pointId: recordPoint.get('id'), cmd: 'choose'},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        checkboxSelDevice.clearSelections();
                        deviceWin.hide();
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            store.reload();
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "保存成功");
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "保存失败！");
                        }
                    }
                });
            }
        }, {
            text: '取消',
            handler: function() {
                checkboxSelDevice.clearSelections();
                deviceWin.hide();
            }
        }]
});
function choosedevice() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能配置装置");
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "您选择了多项，一次只能选择一项");
    }
    else {
        var r = checkboxSel.getSelected();
        var deviceId = r.get('deviceId');
        if (deviceId % 10 === 0) {  //新增
            storeDevice.load({params: {start: 0, limit: _pageSizeSmall, loadType: 'choose'}});
            deviceWin.show();
        } else {   //修改
            Ext.Msg.alert('系统提示', '该测点已安装装置');
        }
    }
}

function unbinddevice() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
    }
    else {

        Ext.MessageBox.confirm('系统提示', '确实要解除所选监测点的装置吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                var jsonDataDevices = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    var ssDevices = records[i].get("deviceId");
                    var startStatus = records[i].get("startStatusCh");
                    if (ssDevices <= 0) {
                        Ext.Msg.alert("系统提示", "所选项中存在未绑定设备的监测点");
                        return;
                    }

                    if (startStatus === '启用') {
                        Ext.Msg.alert("系统提示", "所选项中存在已启动的监测点，只有停用的监测点才可以解除装置");
                        return;
                    }
                    if (i === 0) {
                        jsonData = jsonData + ss;
                        jsonDataDevices = jsonDataDevices + ssDevices;
                    } else {
                        jsonData = jsonData + "," + ss;
                        jsonDataDevices = jsonDataDevices + "," + ssDevices;
                    }
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: unbindServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData, deviceIds: jsonDataDevices},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("系统提示", "所选监测点装置成功解除！");
                                store.reload(); //重新load数据
                            }
                            else {
                                Ext.Msg.alert('系统提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("系统提示", "所选监测点装置解除失败！");
                        }
                    }
                });
            }
        });
    }
}

var startForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'StartForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesStart',
                    width: 180,
                    height: 250,
                    readOnly: true,
                    diable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
                , {
                    name: 'effectTime',
                    id: 'EffectTimeS',
                    width: 180,
                    xtype: 'datefield',
                    fieldLabel: '测点生效日期',
                    format: 'Y-m-d',
                    allowBlank: false
                }
            ],
            buttons: [{
                    text: '启用',
                    iconCls: 'icon-control_play',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                winStart.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        //alert(ids.pointIds);
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.cmd = 'start';
                        Ext.getCmp('StartForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winStart.hide();
                    }
                }]
        }
);
var winStart = new Ext.Window({
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    modal: true,
    items: [startForm]
});
function startpoint() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能配置装置");
    }
    else {
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesStart').setValue(pointNames);
        Ext.getCmp('EffectTimeS').setValue(now);
        winStart.show();
    }
}

var stopForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'StopForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesStop',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    diable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
                , {
                    name: 'stopTime',
                    id: 'StopTime',
                    width: 180,
                    xtype: 'datefield',
                    fieldLabel: '测点停用日期',
                    format: 'Y-m-d',
                    allowBlank: false
                }, {
                    name: 'stopReason',
                    id: 'StopReason',
                    width: 180,
                    height: 100,
                    fieldLabel: '停用原因',
                    xtype: 'textarea'
                }
            ],
            buttons: [{
                    text: '停用',
                    iconCls: 'icon-control_stop',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winStop.hide();
                                store.reload();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        //alert(ids.pointIds);
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.cmd = 'stop';
                        Ext.getCmp('StopForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winStop.hide();
                    }
                }]
        }
);
var winStop = new Ext.Window({
    layout: 'form',
    width: 400,
    autoHeight: true,
    modal: true,
    closeAction: 'hide',
    items: [stopForm]
});
function stoppoint() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
    }
    else {
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesStop').setValue(pointNames);
        Ext.getCmp('StopTime').setValue(now);
        winStop.show();
    }
}

function downloadExcel(){    
    store.baseParams.type=23;
    var encodeParams = Ext.urlEncode(store.baseParams);
    open(basePath+'servlet/common/ExcelFileCreate?'+encodeParams);
}

var excelForm = new Ext.FormPanel({
//renderTo: 'fi-form',
    fileUpload: true,
    width: 500,
    frame: true,
    autoHeight: true,
    bodyStyle: 'padding: 10px 10px 0 10px;',
    labelWidth: 80,
    defaults: {
        anchor: '95%',
        allowBlank: false,
        msgTarget: 'side'
    },
    items: [{
            xtype: 'fileuploadfield',
            id: 'form-file',
            emptyText: '请选择监测点台账Excel文件',
            fieldLabel: '台帐文件',
            name: 'path',
            buttonText: '...',
            buttonCfg: {
                iconCls: 'upload-icon'
            }
        }],
    buttons: [{
            text: '上传导入',
            handler: function() {
                if (excelForm.getForm().isValid()) {
                    excelForm.getForm().submit({
                        url: basePath + 'servlet/common/UploadImportExcelPointListServlet',
                        waitMsg: '正在上传Excel文件...',
                        success: function(excelForm, action) {
                            //Ext.Msg.alert('系统提示', '导入成功');
                            console.log(action.result.msg);
                            //Ext.Msg.alert('a');
                            Ext.Msg.alert('系统提示', action.result.msg);
                        },
                        failure: function(form, action) {
                            switch (action.failureType) {
                                case Ext.form.Action.CONNECT_FAILURE:
                                    Ext.Msg.alert('提示', '网络连接失败');
                                    break;
                                case Ext.form.Action.SERVER_INVALID:
                                    Ext.Msg.alert('提示', action.result.msg);
                                default:
                                    Ext.Msg.alert('提示', action.result.msg);
                            }
                        }

                    });
                }
            }
        }, {
            text: '重置',
            handler: function() {
                excelForm.getForm().reset();
            }
        }]
});
var winExcel = new Ext.Window({
    title: '选择要导入的监测点台帐excel文件',
    layout: 'form',
    modal: true,
    //width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [excelForm]
});
function importFromExcel() {
    winExcel.show();
}

function downloadTemplate() {
    var params = {type: 21}; //下载台帐导入模板
    var encodeParams = Ext.urlEncode(params);
    open('../../servlet/common/ExcelFileCreate?' + encodeParams);
}

function setdevice() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能配置装置");
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "您选择了多项，一次只能选择一项");
    }
    else {
        var r = checkboxSel.getSelected();
        var deviceId = r.get('deviceId');
        if (deviceId < 1) {  //新增
            deviceType = 1;
            Ext.getCmp('SetDeviceForm').getForm().reset();
            modelNew();
        } else {   //修改
            deviceType = 2;
            Ext.getCmp('SetDeviceForm').getForm().loadRecord(checkboxSel.getSelected());
            var temp = checkboxSel.getSelected().get('runTime');
            var r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
            Ext.getCmp('RunTime').setValue(r);
            temp = checkboxSel.getSelected().get('produceTime');
            r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
            Ext.getCmp('ProduceTime').setValue(r);
            temp = checkboxSel.getSelected().get('checkTime');
            r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
            Ext.getCmp('CheckTime').setValue(r);
            temp = checkboxSel.getSelected().get('expireTime');
            r = Date.parseDate(temp, 'yy-m-d H:i:s.u', false);
            Ext.getCmp('ExpireTime').setValue(r);

            temp = checkboxSel.getSelected().get('model');

            if (temp === 'DT3') {
                modelDT3();
            } else if (temp === 'DT4-2') {
                modelDT4();
            } else {

            }

        }
        winSetDevice.setTitle("设置监测点装置");
        winSetDevice.show();
    }
}

var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
                , baseParams: {loadCmd: loadCmd, start: 0, limit: _pageSize, cmd: 'general'}
        , autoLoad: true
    });
    store.on("exception", function(o, type, action, options, response, arg) {
        if (type === "response" && response.responseText) {
            var responseObject = Ext.decode(response.responseText);
            if (responseObject.msg) {
                Ext.Msg.alert("系统消息", responseObject.msg);
                return;
            }
        }
        alert(arg.message);
    });
    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        autoExpandColumn: fieldLabel[12],
        columns: [
            checkboxSel,
            {header: "状态", dataIndex: 'deviceId', width: 40,
                renderer: function(v, metaData, record, rowIndex, colIndex, store) {
                    var value = parseInt(v);
                    var imageName;
                    if (value > 0) {
                        imageName = 'image.png';
                        return "<image src='" + basePath + "image/icon/" + imageName + "'/>";
                    } else
                        return "";
                }
            },
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: '供电局', width: 150, sortable: true, dataIndex: 'company'},
            {header: '部门分县局', width: 100, sortable: true, dataIndex: 'subCompany'},
            {header: '监测点名称', width: 200, sortable: true, dataIndex: 'name'},
            {header: '监测点类型', width: 80, sortable: true, dataIndex: 'pointType'},
            {header: '电网类型', width: 80, sortable: true, dataIndex: 'pointType2'},
            {header: '电压等级', width: 80, sortable: true, dataIndex: 'voltageLevelName', align: 'right'},
            {header: '电压上限', width: 100, sortable: true, dataIndex: 'upperLimit', xtype: 'numbercolumn', format: '0.00', align: 'right'},
            {header: '电压下限', width: 100, sortable: true, dataIndex: 'lowerLimit', xtype: 'numbercolumn', format: '0.00', align: 'right'},
            {header: '所属供电所名称', width: 150, sortable: true, dataIndex: 'shortName'},
            {header: '测点地域', width: 80, sortable: true, dataIndex: 'pointArea'},
            {header: '监测测点位置', width: 80, sortable: true, dataIndex: 'pointPosition'},
            {header: '所属变电站名称', width: 150, sortable: true, dataIndex: 'stationName'},
            {header: '所属变电站电压等级', width: 120, sortable: true, dataIndex: 'stationVoltageLevel'},
            {header: '用户名称', width: 120, sortable: true, dataIndex: 'userName'},
            {header: '公变名称', width: 150, sortable: true, dataIndex: 'publicName'},
            {header: '上报观测', width: 80, sortable: true, dataIndex: 'reportStatusCh'},
            {header: '生效日期', width: 80, sortable: true, dataIndex: 'effectTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '安装位置', width: 200, sortable: true, dataIndex: 'installSite'},
            {header: '装置类别', width: 80, sortable: true, dataIndex: 'deviceType'},
            {header: '生产厂家', width: 120, sortable: true, dataIndex: 'manufactoryName'},
            {header: '装置型号', width: 80, sortable: true, dataIndex: 'model'},
            {header: '通信方式', width: 80, sortable: true, dataIndex: 'commTypeName'},
            {header: '协议名称', width: 80, sortable: true, dataIndex: 'protocolName'},
            {header: '通信卡号', width: 120, sortable: true, dataIndex: 'mobileNo'},
            {header: '装置IP', width: 120, sortable: true, dataIndex: 'ip'},
            {header: '安装日期', width: 80, sortable: true, dataIndex: 'installTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '校验日期', width: 80, sortable: true, dataIndex: 'checkTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '监测点编码', width: 100, sortable: true, dataIndex: 'code'},
            {header: '装置编码', width: 100, sortable: true, dataIndex: 'deviceNo'},
            {header: '终端地址', width: 80, sortable: true, dataIndex: 'terminalNo'},
            {header: '行政区域码', width: 80, sortable: true, dataIndex: 'adminAreaCode'},
            {header: '组编码', width: 80, sortable: true, dataIndex: 'zbm'},
            {header: '唯一码', width: 120, sortable: true, dataIndex: 'uniqueCode'},
            {header: '通道', width: 80, sortable: true, dataIndex: 'channel'},
            {header: '启用停用', width: 80, sortable: true, dataIndex: 'startStatusCh'},
            {header: '停用日期', width: 80, sortable: true, dataIndex: 'stopTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '停用原因', width: 80, sortable: true, dataIndex: 'stopReason'},
            {header: '有效期', width: 80, sortable: true, dataIndex: 'expireTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '装置端口', width: 80, sortable: true, dataIndex: 'port'},
            {header: '出厂日期', width: 80, sortable: true, dataIndex: 'produceTime', xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '管理人员', width: 80, sortable: true, dataIndex: 'realName'},
            {header: '备注', id: '备注', width: 80, sortable: true, dataIndex: 'note'}
            //{header: '投运日期', width: 120, sortable: true, dataIndex: 'runTime', xtype: 'datecolumn', format: 'Y-m-d'},
        ],
        //autoExpandColumn: fieldName[2],
        //renderTo: Ext.getBody(),
        //width: 780,
        //height: 590,
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addnew, hidden: loadCmd === 'normal' ? false : true},
            {text: '修改', iconCls: 'icon-edit', handler: update, hidden: loadCmd === 'normal' ? false : true},
            {text: '批量修改', iconCls: 'icon-edit', handler: batchUpdate, hidden: loadCmd === 'normal' ? false : true},
            {text: '删除', iconCls: 'icon-delete', handler: remove, toolTip: "只删除监测点信息"},
            {text: '完全删除', iconCls: 'icon-delete', handler: removeFull, toolTip: "除监测点信息及设备信息", hidden: loadCmd === 'normal' ? true : false},
            {text: '恢复', iconCls: 'icon-restore', handler: restore, hidden: loadCmd === 'normal' ? true : false},
            {text: '变更单位', iconCls: 'icon-changeOrg', handler: changeOrg, hidden: loadCmd === 'normal' ? false : true},
            {text: '设置装置', iconCls: 'icon-setDevice', handler: setdevice, hidden: loadCmd === 'normal' ? false : true},
            {text: '选择装置', iconCls: 'icon-chooseDevice', handler: choosedevice, hidden: loadCmd === 'normal' ? false : true},
            {text: '解除装置', iconCls: 'icon-removeDevice', handler: unbinddevice, hidden: loadCmd === 'normal' ? false : true},
            {text: '启用', iconCls: 'icon-control_play', handler: startpoint, hidden: true},
            {text: '停用', iconCls: 'icon-control_stop', handler: stoppoint, hidden: true},
            {
                xtype: 'button',
                text: '导出',
                iconCls: 'icon-excel',
                width: 60,
                style: {
                    marginLeft: '20px'
                },
                handler: downloadExcel, 
                hidden: loadCmd === 'normal' ? false : true
            },
            {text: 'Excel导入', iconCls: 'icon-linkratio', handler: importFromExcel, hidden: loadCmd === 'normal' ? false : true},
            '->',
            {text: '下载模板', iconCls: 'icon-linkratio', handler: downloadTemplate, hidden: loadCmd === 'normal' ? false : true}
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        }),
        listeners: {
            'render': function() {
                tbarPoint.render(this.tbar);
            }
        }
    });
    //grid.el.center();
    //store.load({params: {start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
